﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using Aspose.Cells.Charts;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.Systems.Entitys.Permission;
using SHZY.BaseData.Entitys.Entity;
using SHZY.Business.Entitys.Common.Dto.PrintExecute;
using SHZY.Business.Entitys.Dto.customerappeal;
using SHZY.Business.Entitys.Entity;
using SHZY.Business.Entitys.OA;
using SHZY.Business.Interfaces;
using SHZY.Business.Interfaces.VideoRecording;
using SHZY.Business.OA;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.FR;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.Business
{
    /// <summary>
    /// 业务实现：质量申诉.
    /// </summary>
    [ApiDescriptionSettings(Tag = "Business", Name = "QmsBusiCustomerAppeal", Order = 200)]
    [Route("api/Business/[controller]")]
    public class QmsBusiCustomerAppealService : IQmsBusiCustomerAppealService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBusiCustomerAppealEntity> _repository;

        /// <summary>
        /// 多租户事务.
        /// </summary>
        private readonly ITenant _db;

        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 文件服务.
        /// </summary>
        private readonly IFileManager _fileManager;

        /// <summary>
        /// OA.
        /// </summary>

        //private readonly QmsOAService _qmsOAService;

        /// <summary>
        /// 初始化一个<see cref="QmsBusiCustomerAppealService"/>类型的新实例.
        /// </summary>
        public QmsBusiCustomerAppealService(
            ISqlSugarRepository<QmsBusiCustomerAppealEntity> qmsBusiCustomerAppealRepository,
            IDataInterfaceService dataInterfaceService,
            ISqlSugarClient context,
            IUserManager userManager, IFileManager fileManager/*, QmsOAService qmsOAService*/)
        {
            _repository = qmsBusiCustomerAppealRepository;
            _dataInterfaceService = dataInterfaceService;
            _db = context.AsTenant();
            _userManager = userManager;
            _fileManager = fileManager;
            //_qmsOAService = qmsOAService;
        }

        /// <summary>
        /// 获取质量申诉.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<dynamic> GetInfo(string id)
        {
            var customerid = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == id).Select(it => new { id = it.Id }).FirstAsync();
            var customerappealdata = _repository.Context.Queryable<QmsBusiCustomerAppealEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.CustomerId == customerid.id).Select(it => new QmsBusiCustomerAppealListOutput() { id = it.Id, appeaDepartId = it.AppeaDepartId, appealUserId = it.AppealUserId, appeaNo = it.AppeaNo, projectName = it.ProjectName, materialNo = it.MaterialNo, materialName = it.MaterialName, qty = it.Qty, checkedUserId = it.CheckedUserId, problemDescription = it.ProblemDescription, appealDescription = it.AppealDescription, proofMaterials = it.ProofMaterials, remark = it.Remark, status = it.Status,appeaDate=it.AppeaDate }).First();
            if (customerappealdata == null)
            {
                customerappealdata = new QmsBusiCustomerAppealListOutput { id = "", appeaDepartId = "", appealUserId = "", appeaNo = "", projectName = "", materialNo = "", materialName = "", qty = null, checkedUserId = "", problemDescription = "", appealDescription = "", proofMaterials = "", remark = "", status = null,appeaDate=null };
            }
            return customerappealdata;
        }
        /// <summary>
        /// 新建质量申诉.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] QmsBusiCustomerAppealCrInput input)
        {
            var entity = input.Adapt<QmsBusiCustomerAppealEntity>();
            entity.Id = SnowflakeIdHelper.NextId();
            entity.EnabledMark = 1;
            var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
            //提交OA
           // Content content = new Content() {
           //     type = "Complaint",
           //     orderNumber = entity.AppeaNo,
           //     title = "客诉-客户名称-质量申诉流程",
           //     context = "请查阅附件，请审批。",
           //     attachments="",
           //     attachmentsPath=""
           // };
           //await _qmsOAService.SendMessageAsync(content);
        }

        /// <summary>
        /// 更新质量申诉.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] QmsBusiCustomerAppealUpInput input)
        {
            var entity = input.Adapt<QmsBusiCustomerAppealEntity>();
            var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
            {
                it.AppeaDepartId,
                it.AppealUserId,
                it.AppeaDate,
                it.AppeaNo,
                it.ProjectName,
                it.ProjectNameTwo,
                it.MaterialNo,
                it.MaterialName,
                it.Qty,
                it.CheckedUserId,
                it.ProblemDescription,
                it.AppealDescription,
                it.ProofMaterials,
                it.Remark,
                it.Status,
            }).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
        }

        /// <summary>
        /// 质量申述打印.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <param name="exportType">打印类型.</param>
        /// <returns></returns>
        [HttpPost("fastreportPrintCustpmerAppeal")]
        public async Task<dynamic> PrintCustpmerAppeal([FromBody] ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.PDF)
        {
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion
            //获取数据源
            var customeid = await _repository.Context.Queryable<QmsBusiCustomerComplaintEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Id == input.formDataId).Select(it => new QmsBusiCustomerComplaintEntity { Id = it.Id }).FirstAsync();
            var primary = await _repository.Context.Queryable<QmsBusiCustomerAppealEntity>().Where(it => it.CustomerId == customeid.Id && it.DeleteMark == null).
                Select(it => new QmsBusiCustomerAppealListOutput() 
                { 
                    id = it.Id, 
                    appeaDepartId = SqlFunc.Subqueryable<OrganizeEntity>().Where(p => p.Id == it.AppeaDepartId).Select(p => p.FullName),
                    appealUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.AppealUserId).Select(p => p.RealName),
                    appeaDate = it.AppeaDate,
                    appeaNo = it.AppeaNo, 
                    projectName = it.ProjectName, 
                    projectNameTwo = it.ProjectNameTwo, 
                    materialNo = it.MaterialNo, 
                    materialName = it.MaterialName,
                    qty = it.Qty, 
                    checkedUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.CheckedUserId).Select(p => p.RealName),
                    problemDescription = it.ProblemDescription, 
                    appealDescription = it.AppealDescription,
                    proofMaterials = it.ProofMaterials, 
                    remark = it.Remark,
                    status = it.Status 
                }).ToDataTableAsync();
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
            return ms;
        }
    }
}
